﻿using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace ExcelFileMonitor.NPOI.Models
{
    public class ExcelFileEvent
    {
        public string FilePath { get; set; }
        public string FileName => System.IO.Path.GetFileName(FilePath);
        public string Directory => System.IO.Path.GetDirectoryName(FilePath);
        public string SubFolder => GetSubFolderPath();
        public DateTime EventTime { get; set; } = DateTime.Now;
        public long FileSize { get; set; }
        public DateTime LastWriteTime { get; set; }
        public FileEventType EventType { get; set; }
        public Exception Error { get; set; }

        public ExcelFileEvent()
        {
        }

        public ExcelFileEvent(string filePath, FileEventType eventType)
        {
            FilePath = filePath;
            EventType = eventType;

            UpdateFileInfo();
        }

        public void UpdateFileInfo()
        {
            try
            {
                if (System.IO.File.Exists(FilePath))
                {
                    var fileInfo = new System.IO.FileInfo(FilePath);
                    FileSize = fileInfo.Length;
                    LastWriteTime = fileInfo.LastWriteTime;
                }
            }
            catch (Exception ex)
            {
                Error = ex;
            }
        }

        private string GetSubFolderPath()
        {
            if (string.IsNullOrEmpty(FilePath) || string.IsNullOrEmpty(Directory))
                return string.Empty;

            return Directory;
        }

        public override string ToString()
        {
            return $"{EventType}: {FilePath} (Size: {FileSize} bytes, Modified: {LastWriteTime:yyyy-MM-dd HH:mm:ss})";
        }

        public bool IsValidExcelFile()
        {
            if (string.IsNullOrEmpty(FilePath))
                return false;

            var extension = System.IO.Path.GetExtension(FilePath).ToLower();
            return extension == ".xlsx" || extension == ".xls";
        }
    }

    public enum FileEventType
    {
        Created,
        Modified,
        Deleted,
        Renamed,
        Error
    }
}
